import { writeFileSync, existsSync, mkdirSync, readFileSync, unlinkSync, statSync } from "fs";
import { defineEventHandler, readBody, readMultipartFormData, getMethod, createError } from "h3";
import { join } from "path";

export default defineEventHandler(async (event) => {
  const method = getMethod(event);
  
  // Ensure directories exist
  const shareDir = "share-lan";
  const dataDir = "data-files";
  
  if (!existsSync(shareDir)) {
    mkdirSync(shareDir, { recursive: true });
  }
  if (!existsSync(dataDir)) {
    mkdirSync(dataDir, { recursive: true });
  }

  const metaDataPath = `${dataDir}/lan-share-files.json`;

  // Helper function to read metadata
  const readMetadata = () => {
    if (existsSync(metaDataPath)) {
      return JSON.parse(readFileSync(metaDataPath, "utf-8"));
    }
    return { files: [], timestamp: new Date().toISOString() };
  };

  // Helper function to write metadata
  const writeMetadata = (data: any) => {
    writeFileSync(metaDataPath, JSON.stringify(data, null, 2), "utf-8");
  };

  if (method === 'GET') {
    // Get file list
    const metadata = readMetadata();
    return { files: metadata.files || [] };
  }

  if (method === 'POST') {
    // First try to read multipart form data (file upload)
    try {
      const formData = await readMultipartFormData(event);
      
      if (formData && formData.length > 0) {
        // Handle file upload
        const uploadedFiles = [];
        const metadata = readMetadata();

        for (const field of formData) {
          if (field.name === 'files' && field.filename && field.data) {
            const filename = field.filename;
            const filePath = join(shareDir, filename);
            
            // Write file to disk
            writeFileSync(filePath, field.data);
            
            // Get file stats
            const stats = statSync(filePath);
            
            // Add to metadata
            const fileInfo = {
              filename,
              originalName: filename,
              size: stats.size,
              uploadTime: new Date().toISOString(),
              mimeType: field.type || 'application/octet-stream'
            };
            
            // Remove existing file with same name from metadata
            metadata.files = metadata.files.filter((file: any) => file.filename !== filename);
            metadata.files.push(fileInfo);
            uploadedFiles.push(fileInfo);
          }
        }

        metadata.timestamp = new Date().toISOString();
        writeMetadata(metadata);

        return { success: true, message: 'Files uploaded successfully', files: uploadedFiles };
      }
    } catch {
      // If multipart parsing fails, try to read JSON body
    }

    // If no multipart data, try to read JSON body (for delete actions)
    try {
      const body = await readBody(event);
      const { action, filename } = body;

      if (action === 'delete') {
        // Delete file
        const filePath = join(shareDir, filename);
        if (existsSync(filePath)) {
          unlinkSync(filePath);
          
          // Update metadata
          const metadata = readMetadata();
          metadata.files = metadata.files.filter((file: any) => file.filename !== filename);
          metadata.timestamp = new Date().toISOString();
          writeMetadata(metadata);
          
          return { success: true, message: 'File deleted successfully' };
        }
        throw createError({
          statusCode: 404,
          statusMessage: "File not found",
        });
      }
    } catch {
      // If both fail, return error
      throw createError({
        statusCode: 400,
        statusMessage: "Invalid request format",
      });
    }
  }

  throw createError({
    statusCode: 405,
    statusMessage: "Method not allowed",
  });
}); 